let express = require("express");
const router = express.Router();
const format = require("../public/retention");
const connect = require("../config/config.js");
const log4js  = require("../config/log.js");
let logger=log4js.getLogger("info");
//留存率
router.post("/getfirstday", (req, res) => {
	const endDate = parseInt(req.body.endDate);
	connect(function(err, db) {
		if (err) {
			logger.info("数据库链接失败！")
		} else {
			//根据系统的当前时间查询出最早注册的时间是多少
			db.collection("register").find({
				"register_time": {
					"$lt": endDate
				}
			}).sort({
				"register_time": 1
			}).limit(1).toArray((err, data) => {
				res.send(data)
			})
		}
	})
});
//留存率
router.post("/getretention", (req, res) => {
	let start_time = parseInt(req.body.start_time);
	let next_time = start_time + (24 * 3600);
	connect(function(err, db) {
		if (err) {
			return;
		} else {
			let obj = {};let count1 = 0;let count2 = 0;
			let count3 = 0;let count4 = 0;let counts = 0;
			let dau = 0;let day = 0;let arr = [];
			let uid_s = [];let retention_Arr = [];
			if (err) {
				logger.info(err);
				return;
			} else {
				db.collection("register").aggregate([{
						$match: {
							register_time: {
								$gte: start_time,
								$lt: next_time
							}
						}
					},
					{
						$group: {
							_id: {
								uid: "$uid",
								register_time: "$register_time"
							},
							count: {
								$sum: 1
							}
						}
					},
					{
						$sort: {
							_id: -1
						}
					}
				]).toArray(function(err, result) {
					if (err) {
						return;
					} else {
						result.forEach(item => {
							counts += item.count;
							uid_s.push(item._id.uid)
						});
						db.collection("sign_in").aggregate([{
								$match: {
									register_time: {
										$gte: start_time,
										$lt: next_time
									}
								}
							},
							{
								$group: {
									_id: {
										uid: "$uid",
										register_time: "$register_time",
										sign_in_date: "$sign_in_date"
									},
									count: {
										$sum: 1
									}
								}
							},
							{
								$sort: {
									_id: -1
								}
							}
						]).toArray(function(err, data) {
							//先将data遍历一下，取出对应的登录时间和注册时间去处掉所有的后面的时分秒后，直接存到另一个数组中，然后通过数组可以实现去重
							data.forEach(item => {
								let time1 = format.formatDate(new Date(item._id.sign_in_date * 1000));
								let time2 = format.formatDate(new Date(item._id.register_time * 1000));
								let datetime1 = (new Date(Date.parse(time1.replace(/-/g, "/"))).getTime()) / 1000;
								let datetime2 = (new Date(Date.parse(time2.replace(/-/g, "/"))).getTime()) / 1000;
								let objs = {
									count: item.count,
									register_time: datetime2,
									sign_in_date: datetime1,
									uid: item._id.uid
								};
								arr.push(objs)
							});
							const uid = "uid";
							//去掉uid相同的数据
							const newArr = arr.reduce((all, next) => all.some((atom) => atom[uid] === next[uid]) ? all : [...all,
								next
							], []);
							newArr.forEach(item => {
								//判断登录表中的uid是否在注册表中存在
								let uid = uid_s.indexOf(parseInt(item.uid));
								if (uid > -1) {
									retention_Arr.push(item);
									dau += item.count;
								}
							});
							retention_Arr.forEach(item => {
								if (item.register_time > item.sign_in_date) {
									return;
								} else {
									let count = item.sign_in_date - item.register_time;
									day = Math.floor(count / (24 * 3600));
									// 次日留存数
									if (day > 0 && day === 1) {
										count1 += item.count
									}
									// 三日留存数
									if (day > 0 && day === 3) {
										count2 += item.count
									}
									//七日留存数
									if (day > 0 && day === 7) {
										count3 += item.count
									}
									//十五日留存数
									if (day > 0 && day === 15) {
										count4 += item.count
									}
								}
							});
							let time = format.formatDate(new Date(start_time * 1000));
							if (counts > 0) {
								obj = {
									time: time,
									dau: dau,
									next_day_retention_rate: Math.round(count1 / counts * 10000) / (100.0).toFixed(2) + "%",
									three_day_retention_rate: Math.round(count2 / counts * 10000) / (100.0).toFixed(2) + "%",
									seven_day_retention_rate: Math.round(count3 / counts * 10000) / (100.0).toFixed(2) + "%",
									fifteen_day_retention_rate: Math.round(count4 / counts * 10000) / (100.0).toFixed(2) + "%",
								};
								res.send(obj);
							}
						})
					}
				})
			}
		}
	})
});
module.exports = router;
